package com.yifushidai.utils;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.HttpMethod;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by lightClouds917
 * Date 2018/2/7
 * Description:aliyunOSSUtil
 */
public class AliyunOSSUtil {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(AliyunOSSUtil.class);

    private static String END_POINT = "oss-cn-shanghai.aliyuncs.com";
    private static String ACCESS_KEY_ID = "LTAIo6s88MTyjUKu";
    private static String ACCESS_KEY_SECRET = "OQQIGsXBPRgLGiNnN1PvusF9hqTB1G";
    public static String BUCKET_NAME1 = "shisu";
    private static String SFZ_FILE_HOST = "sfz";
    private static String IMAGE_FILE_HOST = "img";

    public static String getSfzUrl(String mac, MultipartFile fileupload, String type, String num) throws OSSException, ClientException, IOException {
        String ext = fileupload.getOriginalFilename().substring(fileupload.getOriginalFilename().lastIndexOf("."));
        String filePath = SFZ_FILE_HOST + "/" + mac + "/" + num + "_" + type + ext;
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 上传文件
        ossClient.putObject(BUCKET_NAME1, filePath, fileupload.getInputStream());
        // 设置URL过期时间为100年，默认这里是int型，转换为long型即可
        Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 100);
        // 生成URL
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(BUCKET_NAME1, filePath);
        request.setMethod(HttpMethod.GET);
        request.setExpiration(expiration);
//        request.setProcess("style/unaudited");
        request.setProcess("style/audited");
        URL url = ossClient.generatePresignedUrl(request);
        return url.toString();
    }

    public static String getImgUrl(String folder, MultipartFile fileupload) throws OSSException, ClientException, IOException {
        String filePath = IMAGE_FILE_HOST + "/" + folder + "/" + UUIDUtils.creatUUID() + "_" + fileupload.getOriginalFilename();
        // 创建OSSClient实例
        OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        // 上传文件
        ossClient.putObject(BUCKET_NAME1, filePath, fileupload.getInputStream());
        // 设置URL过期时间为100年，默认这里是int型，转换为long型即可
        Date expiration = new Date(new Date().getTime() + 3600L * 1000 * 24 * 365 * 100);
        // 生成URL
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(BUCKET_NAME1, filePath);
        request.setMethod(HttpMethod.GET);
        request.setExpiration(expiration);
        URL url = ossClient.generatePresignedUrl(request);
        return url.toString();
    }

    /**
     * 上传文件
     *
     * @param file
     * @return
     */
    public static String upload(File file) throws ParseException {
        logger.info("=========>OSS文件上传开始：" + file.getName());
        OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
        try {
            //容器不存在，就创建
            if (!ossClient.doesBucketExist(BUCKET_NAME1)) {
                ossClient.createBucket(BUCKET_NAME1);
                CreateBucketRequest createBucketRequest = new CreateBucketRequest(BUCKET_NAME1);
                createBucketRequest.setCannedACL(CannedAccessControlList.Private);
                ossClient.createBucket(createBucketRequest);
            }
            //创建文件路径
            String fileUrl = SFZ_FILE_HOST + "/" + DateUtils.getCurrent() + "/" + UUIDUtils.creatUUID() + "_" + file.getName();
            //上传文件
            PutObjectResult result = ossClient.putObject(new PutObjectRequest(BUCKET_NAME1, fileUrl, file));
            //设置权限 这里是公开读
            ossClient.setBucketAcl(BUCKET_NAME1, CannedAccessControlList.Private);
            if (null != result) {
                logger.info("==========>OSS文件上传成功,OSS地址：" + fileUrl);
                return fileUrl;
            }
        } catch (OSSException oe) {
            logger.error(oe.getMessage());
        } catch (ClientException ce) {
            logger.error(ce.getMessage());
        } finally {
            //关闭
            ossClient.shutdown();
        }
        return null;
    }

    /**
     * 删除Object
     *
     * @param fileKey
     * @return
     */
    public static String deleteObject(String fileKey) {
        logger.info("=========>OSS文件删除开始");
        try {
            OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);

            if (!ossClient.doesBucketExist(BUCKET_NAME1)) {
                logger.info("==============>您的Bucket不存在");
                return "您的Bucket不存在";
            } else {
                logger.info("==============>开始删除Object");
                ossClient.deleteObject(BUCKET_NAME1, fileKey);
                logger.info("==============>Object删除成功：" + fileKey);
                return "==============>Object删除成功：" + fileKey;
            }
        } catch (Exception ex) {
            logger.info("删除Object失败", ex);
            return "删除Object失败";
        }
    }

    /**
     * 查询文件名列表
     *
     * @param bucketName
     * @return
     */
    public static List<String> getObjectList(String bucketName) {
        List<String> listRe = new ArrayList<>();
        try {
            logger.info("===========>查询文件名列表");
            OSSClient ossClient = new OSSClient(END_POINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
            //列出blog目录下今天所有文件
//            listObjectsRequest.setPrefix(ConstantProperties.JAVA4ALL_FILE_HOST + "/" + format.format(new Date()) + "/");
            listObjectsRequest.setPrefix(SFZ_FILE_HOST + "/");
            ObjectListing list = ossClient.listObjects(listObjectsRequest);
            for (OSSObjectSummary objectSummary : list.getObjectSummaries()) {
                listRe.add(objectSummary.getKey());
            }
            return listRe;
        } catch (Exception ex) {
            logger.info("==========>查询列表失败", ex);
            return new ArrayList<>();
        }
    }
}
